<script setup lang="ts">
  import { PropType, ref, watch } from 'vue'
  import { ElMessage, FormInstance } from 'element-plus'
  import { useAddChildType } from '@/services/pages/common/type'

  const visible = defineModel('visible', { type: Boolean, default: false })
  const props = defineProps({
    parentType: {
      type: Object,
      required: true,
    },
    type: {
      type: String as PropType<'commodity' | 'network' | 'order'>,
      required: true,
    },
    orderModuleId: String,
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  const { form, loading, submit, resetForm } = useAddChildType(props.type)

  // 表单验证规则
  const rules = {
    name: [
      { required: true, message: '请填写分类名称', trigger: ['blur', 'change'] },
      {
        validator: (rule, value: string, callback) => {
          let repeatNum = 0
          form.value.childData.forEach((childLevel) => {
            if (value === childLevel.name) {
              repeatNum += 1
            }
          })
          if (repeatNum > 1) {
            callback(
              new Error(
                props.parentType.level === 1 ? '二级分类名称不允许重复' : '三级分类名称不允许重复',
              ),
            )
            return
          }
          callback()
        },
        trigger: ['blur', 'change'],
      },
    ],
  }

  /**
   * 关闭弹窗
   */
  const closeDialog = () => {
    visible.value = false
    resetForm()
  }

  // 表单组件实例
  const formInstance = ref<FormInstance | null>(null)

  /**
   * 添加子类
   */
  const onAddChildCommodityType = () => {
    if (props.type === 'order') {
      form.value.childData.push({
        id: null,
        name: '',
        parentId: form.value.id,
        status: false,
        childData: [],
        sort: 0,
      })
      return
    }

    form.value.childData.push({
      id: null,
      name: '',
      parentId: form.value.id,
      status: false,
      childData: [],
    })
  }

  /**
   * 保存
   */
  const onSave = async () => {
    if (!formInstance.value) {
      return
    }
    try {
      await formInstance.value.validate()
      const orderModuleId = props.orderModuleId || ''
      const res = await submit(orderModuleId)
      ElMessage({
        type: res.code === 20000 ? 'success' : 'error',
        message: res.message,
        duration: 5000,
        plain: true,
        showClose: true,
      })
      if (res.code === 20000) {
        visible.value = false
        emits('update')
        resetForm()
      }
    } catch (e) {
      // e
    }
  }

  /**
   * 移除子类
   * @param {number} childTypeIndex - 子类索引
   */
  const handleDelChildType = (childTypeIndex: number) => {
    form.value.childData.splice(childTypeIndex, 1)
  }

  /**
   * 将工单子类的sort字段转为纯数字
   * @param {Nmber} childIndex - 子类索引
   */
  const orderChildTypeSortToNum = (childIndex: number) => {
    form.value.childData[childIndex].sort = Number(
      form.value.childData[childIndex].sort.toString().replace(/[^\d]/g, ''),
    )
  }

  watch(visible, (value) => {
    if (value) {
      if (props.type === 'order') {
        form.value = {
          id: props.parentType.id,
          name: props.parentType.name,
          status: props.parentType.status,
          childData: [],
          parentId: props.parentType.parentId,
          sort: props.parentType.sort,
        }
        return
      }
      if (['commodity', 'network'].includes(props.type)) {
        form.value = {
          id: props.parentType.id,
          name: props.parentType.name,
          status: props.parentType.status,
          childData: [],
          parentId: props.parentType.parentId,
        }
      }
    }
  })
</script>

<template>
  <h-drawer
    v-model="visible"
    title="添加子类"
    :width="800"
    unit="px"
    :loading="loading"
    @close="closeDialog"
  >
    <el-form
      ref="formInstance"
      class="modal_form_content"
      inline-message
      label-position="top"
      :model="form"
    >
      <el-form-item label="父级分类名称" class="disable_form_item">
        <template #label>
          <div class="label">
            <span>{{ props.parentType.level === 1 ? '父级分类名称' : '二级分类名称' }}</span>
            <h-link @click="onAddChildCommodityType">{{
              props.parentType.level === 1 ? '添加二级分类' : '添加三级分类'
            }}</h-link>
          </div>
        </template>
        <el-input :model-value="props.parentType.name" disabled />
      </el-form-item>

      <div
        v-for="(childCommodityType, childCommodityTypeIndex) in form.childData"
        :key="childCommodityTypeIndex"
        class="child_level_form_item_list"
      >
        <el-form-item
          :prop="`childData[${childCommodityTypeIndex}][name]`"
          :label="props.parentType.level === 1 ? '二级分类名称' : '三级分类名称'"
          :rules="rules.name"
        >
          <div class="child_name_form_item_content">
            <el-input
              v-model.trim="form.childData[childCommodityTypeIndex].name"
              :placeholder="
                props.parentType.level === 1 ? '请输入二级分类名称' : '请输入三级分类名称'
              "
            />
            <h-link :height="28" type="error" @click="handleDelChildType(childCommodityTypeIndex)"
              >删除</h-link
            >
          </div>
        </el-form-item>

        <el-form-item label="分类状态" class="same_line">
          <div class="status-container">
            <el-radio-group v-model="form.childData[childCommodityTypeIndex].status">
              <el-radio :value="false">启用</el-radio>
              <el-radio :value="true">禁用</el-radio>
            </el-radio-group>

            <div v-if="props.type === 'order'" class="order-sort">
              <div class="label">工单排序</div>
              <el-input
                v-model.trim="form.childData[childCommodityTypeIndex].sort"
                placeholder="请输入工单排序"
                @input="orderChildTypeSortToNum(childCommodityTypeIndex)"
              />
            </div>
          </div>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <h-button is-modal type="primary" @click="onSave">保存</h-button>
      <h-button is-modal @click="closeDialog">取消</h-button>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  .modal_form_content {
    :deep(.el-form-item__label) {
      padding: 0;
    }

    .disable_form_item {
      .label {
        width: 100%;
        display: flex;
        justify-content: space-between;
        width: calc(100% - 24px - 5px);
      }

      :deep(.el-input) {
        width: calc(100% - 24px - 5px);
      }
    }

    .child_level_form_item_list {
      display: flex;
      flex-direction: column;
      row-gap: 4px;

      .child_name_form_item_content {
        display: flex;
        width: 100%;
        column-gap: 5px;
        height: 28px;

        :deep(.el-input) {
          flex: 1;
        }
      }

      .status-container {
        display: flex;
        align-items: center;

        .order-sort {
          margin-left: 48px;
          display: flex;
          column-gap: 7px;

          .label {
            white-space: nowrap;
            height: 16px;
            line-height: 16px;
            margin-right: 5px;
            color: #606266;
          }

          :deep(.el-input) {
            .el-input__wrapper {
              height: 16px !important;

              .el-input__inner {
                height: 16px;
                line-height: 16px;
              }
            }
          }
        }
      }
    }
  }
</style>
